package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/goburrow/modbus"
)

func ReadData() {
	// Modbus TCP
	handler := modbus.NewTCPClientHandler("localhost:502")
	handler.Timeout = 10 * time.Second
	handler.SlaveId = 1
	handler.Logger = log.New(os.Stdout, "test: ", log.LstdFlags)
	// Connect manually so that multiple requests are handled in one connection session
	err := handler.Connect()
	if err != nil {
	}
	defer handler.Close()

	client := modbus.NewClient(handler)
	for {
		results, err := client.ReadHoldingRegisters(0, 2)
		if err != nil {
			err := handler.Connect()
			client = modbus.NewClient(handler)
			if err != nil {
				continue
			}
			fmt.Println("ReadHoldingRegisters", err)
		}
		fmt.Println(results)
		time.Sleep(1 * time.Second)
	}
}

func pollRegisters(address string, start, quantity uint16) {
	for {
		handler := modbus.TCPClientHandler{
			Address: address,
			Timeout: 3 * time.Second,
		}

		err := handler.Connect()
		if err != nil {
			log.Println("连接失败，稍后重试:", err)
			time.Sleep(5 * time.Second)
			continue
		}

		client := modbus.NewClient(&handler)

		for {
			results, err := client.ReadHoldingRegisters(start, quantity)
			if err != nil {
				log.Println("读取失败，断开并重连:", err)
				break // 跳出内层循环，重新连接
			}
			log.Println("读取成功:", results)
			time.Sleep(10 * time.Second)
		}

		handler.Close()
	}
}


}
